/**
 * class nwsim
 */

package nwsim;

public class NwSim {
	
	private static Node[] nodeArray;
	private static Channel channel;
	public static int ETX1 = 0, ETX2 = 0, ETX3 = 0;
	static int killCount = 0;
	
	public static void main(String[] args) {
		channel = new Channel();
		initNodes();
		discoverNeighbors();
		System.out.println("Starting simulation...");
		startSimulation();
	}
	
	static void initNodes() {
		nodeArray = new Node[Constants.nodeCount];
		for(int i=0; i<Constants.nodeCount; i++) {
			nodeArray[i] = new Node(i, getCoordinates(i));
		}
	}
	
	static Coordinates getCoordinates(int nodeID) { //give some random coordinates, neighbors are hard-coded anyways!
		Coordinates pos = new Coordinates();
		
		switch(nodeID) {
			
			case 0: pos.x = 0; 		pos.y = 0; 		break;
			case 1: pos.x = 500; 	pos.y = 0; 		break;
			case 2: pos.x = 100; 	pos.y = 200; 	break;
			case 3: pos.x = 150; 	pos.y = 130;	break;
			case 4: pos.x = 200; 	pos.y = 200;	break;
			default: System.out.println("Are you kidding me!!!"); break;
		}
		
		return pos;
	}
	
	static void discoverNeighbors() {
		for(int i=0; i<Constants.nodeCount; i++) {
			
			for(int j=0; j<Constants.nodeCount; j++) {
				if(i==j) continue;
				
				double prr = 0;
				switch(i) {
					case 0: {
						if(j==1)		prr = 1;		
						else if(j==3)	prr = 0;		//no neighbors for node 3
					}
					break;
					
					case 1: {
						if(j==0)		prr = 1;		
						else if(j==2)	prr = 0.3;
						else if(j==4)	prr = 1;	//TODO: give good but non-unit probability	
					}
					break;
					
					case 2: {
						if(j==1)		prr = 0.3;		
						else if(j==3)	prr = 0;		//no neighbors for node 3
						else if(j==4)	prr = 1;	//TODO	
					}
					break;
					
					case 3: {
						/*if(j==0)		prr = 1;
						else if(j==2)	prr = 1;*/ 		//no neighbors for node 3
					}
					break;
					
					case 4: {						//TODO
						if(j==1)		prr = 1;
						else if(j==2)	prr = 1;
					}
					break;
				}
				if(prr != 0)
					nodeArray[i].addNeighbor(j, prr);
				
			}
		}
	}
	
	public static Channel getChannel() {
		return channel;
	}
	
	static void startSimulation() {
		for(int i=0; i<Constants.nodeCount; i++) {
			nodeArray[i].start();
		}
	}
	
	public static void stopSimulation() {
		killCount++;
		if(killCount == 2) {
			for(int i=0; i<Constants.nodeCount; i++) {
				nodeArray[i].stopThread = true;
				nodeArray[i].interrupt();
			}
			channel.cancel();
			System.exit(0);
		}
	}
}
